<script lang="ts" setup>
import {onBeforeUnmount, reactive, watch} from "vue";
import DynamicForm from "@/components/DynamicForm3/index.vue";
import {EventFirstParam, FormConfigItem} from "@/components/DynamicForm3/types.ts";
import {ElMessageBox} from "element-plus";
import notiIcon from "../../assets/layouts/logo.png";
import {TimeUtils} from "@/utils/TimeUtils.ts";


const howOftenYouAreNotifiedKey='/workUtils.comData.howOftenYouAreNotified'
const oneTimeTasksKey='/workUtils.comData.oneTimeTasks'
// 组件数据
const comData = reactive({
  howOftenYouAreNotified: JSON.parse(localStorage.getItem(howOftenYouAreNotifiedKey)) as any[] || [],
  formConfigList1: [
    {
      label: '名称',
      prop: 'name',
      type: 'input',
    },
    {
      label: '间隔/s',
      prop: 's',
      type: 'inputNumber',
    },
    {
      label: '是否启用',
      prop: 'enable',
      type: 'switch',
      props: {
        'active-value': '1',
        'inactive-value': '0'
      }
    },
  ] as FormConfigItem[],
  formConfigList2: [
    {
      label: '名称',
      prop: 'name',
      type: 'input',
    },
    {
      label: '执行时间',
      prop: 's',
      type: 'datePicker',
      props:{
        type: 'datetime',
        'value-format': 'YYYY-MM-DD HH:mm:ss'
      },
      events: {
        change(params: EventFirstParam,value) {
          params.formData.enable = '1'
        }
      }
    },
    {
      label: '是否启用',
      prop: 'enable',
      type: 'switch',
      props: {
        disabled: true,
        'active-value': '1',
        'inactive-value': '0'
      }
    },
  ] as FormConfigItem[],
  oneTimeTasks: JSON.parse(localStorage.getItem(oneTimeTasksKey)) as any[] || [],
})

// 开启定时任务，一毫秒执行一次
let timeer = setInterval(()=>{
  comData.howOftenYouAreNotified.forEach(item=>{
    if(item.enable === '1') {
      if(Date.now() - (item.lastTime || 0) > item.s * 1000) {
        item.lastTime = Date.now()
        new Notification("每多长时间通知一次", { body: item.name, icon: notiIcon });
      }
    }
  })
  let dels = []
  comData.oneTimeTasks.forEach((item,index)=>{
    if(item.enable === '1') {
      if(TimeUtils.parseTimeToDate(item.s)<Date.now()) {
        new Notification("一次性任务", { body: item.name, icon: notiIcon });
        dels.push(index)
      }
    }
  })
  if(dels.length) {
    dels.reverse().forEach(item=>{
      comData.oneTimeTasks.splice(item,1)
    })
    dels=[]
  }
},1)

onBeforeUnmount(()=>{
  clearInterval(timeer)
})

watch(()=>comData.howOftenYouAreNotified,()=>{
  localStorage.setItem(howOftenYouAreNotifiedKey,JSON.stringify(comData.howOftenYouAreNotified))
},{deep: true})
watch(()=>comData.oneTimeTasks,()=>{
  localStorage.setItem(oneTimeTasksKey,JSON.stringify(comData.oneTimeTasks))
},{deep: true})

// 安全上下文: 此项功能仅在一些支持的浏览器的安全上下文（HTTPS）中可用。
function askNotificationPermission() {
  // 检查浏览器是否支持通知
  if (!("Notification" in window)) {
    console.log("此浏览器不支持通知。");
    return;
  }
  Notification.requestPermission().then((permission) => {
    if(permission === "granted") {
      console.log("允许创建通知")
    }
  });
}
// 申请权限
askNotificationPermission()

function howOftenYouAreNotifiedClick(target,item = {},index = 0) {
  if(target === 'add') {
    comData.howOftenYouAreNotified.push({})
  } else if(target === 'del') {
    ElMessageBox.confirm(
      '是否删除',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        comData.howOftenYouAreNotified.splice(index,1)
      })
  }
}

function oneTimeTasksClick(target,item = {},index = 0) {
  if(target === 'add') {
    comData.oneTimeTasks.push({})
  } else if(target === 'del') {
    ElMessageBox.confirm(
      '是否删除',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        comData.oneTimeTasks.splice(index,1)
      })
  }
}
</script>

<template>
  <div>
    <el-card header="每多长时间通知一次">
      <el-button
        @click="howOftenYouAreNotifiedClick('add')"
        type="primary"
      >添加一个</el-button>
      <div v-for="(item,index) in comData.howOftenYouAreNotified" :key="'comData.howOftenYouAreNotified'+index">
        <el-divider />
        <DynamicForm
          v-model="comData.howOftenYouAreNotified[index]"
          :form-config-list="comData.formConfigList1"
          :created-init-value="false"
        ></DynamicForm>
        <el-button
          @click="howOftenYouAreNotifiedClick('del',item,index)"
          type="danger"
        >删除</el-button>
      </div>
    </el-card>
    <el-card header="一次性任务">
      <el-button
        @click="oneTimeTasksClick('add')"
        type="primary"
      >添加一个</el-button>
      <div v-for="(item,index) in comData.oneTimeTasks" :key="'comData.oneTimeTasks'+index">
        <el-divider />
        <DynamicForm
          v-model="comData.oneTimeTasks[index]"
          :form-config-list="comData.formConfigList2"
          :created-init-value="false"
        ></DynamicForm>
        <el-button
          @click="oneTimeTasksClick('del',item,index)"
          type="danger"
        >删除</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">

</style>
